package org.jeecg.modules.cqb.util;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @ProjectName cqb
 * @Package org.jeecg.modules.cqb.util
 * @Name NdeUploadFileServerUtil
 * @Author ChenJ
 * @Date 2021/12/2 0007 下午 14:10
 * @Version 1.0  上传文件到文件服务器上（CentOS系统服务器）
 */
@Component
public class FTPUtil {


    private static String host;
    @Value(value = "${ftp-centos.host}")
    public  void setHost(String hostName){
        host = hostName;
    }

    private static Integer port;
    @Value(value = "${ftp-centos.port}")
    public  void setPort(Integer portName) {
        port = portName;
    }

    private static String user;
    @Value(value = "${ftp-centos.user}")
    public  void setUser(String userName) {
        user = userName;
    }

    private static String password;
    @Value(value = "${ftp-centos.password}")
    public  void setPassword(String passwordName) {
        password = passwordName;
    }



    private static String picBasePath;
    @Value(value = "${ftp-centos.picBasePath}")
    public  void setPicBasePath(String picBasePath) {
        FTPUtil.picBasePath = picBasePath;
    }

    private static String fileBasePath;
    @Value(value = "${ftp-centos.fileBasePath}")
    public  void setFileBasePath(String fileBasePath) {
        FTPUtil.fileBasePath = fileBasePath;
    }

    //上传文件
    public static void sshSftp(HttpServletResponse response,  byte[] bytes, String fileName, String type,String fielType) throws Exception {
        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();
        if (port<= 0) {
            //连接服务器，采用默认端口
            session = jsch.getSession(user, host);
        } else {
            //采用指定的端口连接服务器
            session = jsch.getSession(user, host, port);
        }

        //如果服务器连接不上，则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }
        //设置登陆主机的密码
        session.setPassword(password);
        //设置第一次登陆的时候提示，可选值：(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);
        OutputStream outstream = null;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //进入服务器指定的文件夹
            sftp.cd("file".equals(fielType)?fileBasePath: picBasePath);
            //列出服务器指定的文件列表
//            Vector v = sftp.ls("*");
//            for(int i=0;i<v.size();i++){
//                System.out.println(v.get(i));
//            }
            //以下代码实现从本地上传一个文件到服务器，如果要实现下载，对换以下流就可以了
            if("get".equals(type)){//读取文件
                InputStream is = sftp.get(fileName);
                response.setContentType("application/octet-stream;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));//下载时浏览器显示的名称
                OutputStream os = response.getOutputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                byte[] buff = new byte[1024];
                int i = bis.read(buff);
                while (i != -1) {
                    os.write(buff, 0, buff.length);
                    os.flush();
                    i = bis.read(buff);
                }
                os.close();
                is.close();
            }else if("put".equals(type)){//上传文件
                outstream = sftp.put(fileName);
                outstream.write(bytes);
            }else if("del".equals(type)){////删除
                sftp.rm(fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流操作
            if (outstream != null) {
                outstream.flush();
                outstream.close();
            }
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
    }


    //上传文件
    public static InputStream sshSftp(String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();
        if (port<= 0) {
            //连接服务器，采用默认端口
            session = jsch.getSession(user, host);
        } else {
            //采用指定的端口连接服务器
            session = jsch.getSession(user, host, port);
        }

        //如果服务器连接不上，则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }
        //设置登陆主机的密码
        session.setPassword(password);
        //设置第一次登陆的时候提示，可选值：(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        session.connect(30000);
        InputStream is = null;
        InputStream is1 = null;
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //进入服务器指定的文件夹
            sftp.cd(picBasePath);
            is =  sftp.get(fileName);
            is1 = sftp.get("alipay_11.png");
            ImageEntity item = new ImageEntity();
            item.setWidth(100);
            item.setHeight(100);
            item.setData(IOUtils.toByteArray(is1));
            item.setType(ImageEntity.Data);
            params.put("picture", item);

            WordUtil.exportWord2(is, fileName, params,request ,response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流操作
            if (is != null) {
                is.close();
            }
            if (is1 != null) {
                is1.close();
            }
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
        return null;
    }

    //读取文件resours文件
    public static void getLocalFiles(){
        String pdfFilePath = "templates/test.pdf";
        try{
            Resource resource = new ClassPathResource(pdfFilePath);
            //通过如下方法可以转Resource换成InputStream
            InputStream is = resource.getInputStream();
        }catch (Exception e){
            e.printStackTrace();
        }

    }


}